package com.example.a2007dou_shop.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.a2007dou_shop.entity.LoginEntity
import com.example.a2007dou_shop.entity.SendCodeEntity
import com.example.a2007dou_shop.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    //密码登录返回值
    val loginSuccess = MutableLiveData<LoginEntity>()
    val loginFail = MutableLiveData<String>()

    fun login(username:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map["name"] = username
                map["password"] = password
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.login(body)
                loginSuccess.value = result
            }catch (e:Exception){
                loginFail.value = e.message
            }
        }
    }
    //退出登录的返回值
    val logoutSuccess = MutableLiveData<LoginEntity>()
    val logoutFail = MutableLiveData<String>()
    fun logout(){
        viewModelScope.launch {
            try {
                val result = apiServer.logout()
                logoutSuccess.value = result
            }catch (e:Exception){
                logoutFail.value = e.message
            }
        }
    }
    //获取登录验证码
    val sendSuccess = MutableLiveData<SendCodeEntity>()
    val sendFail = MutableLiveData<String>()
    fun sendlcode(phone:String){
        viewModelScope.launch {
            try {
                val result = apiServer.sendlcode(phone)
                sendSuccess.value = result
            }catch (e:Exception){
                sendFail.value = e.message
            }
        }
    }
    //验证码登录
    val logincodeSuccess = MutableLiveData<LoginEntity>()
    val logincodeFail = MutableLiveData<String>()
    fun logincode(phone:String,code:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["phone"] = phone
                map["code"] = code
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.logincode(body)
                logincodeSuccess.value = result

            }catch (e:Exception){
                logincodeFail.value = e.message
            }
        }
    }
}